package com.example.smartcity.http

import android.util.Log
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException

/**
 * @Author: Tailyou(祝文飞)
 * @CreateDate: 2021/10/7 13:29
 * @Description: 网络请求-回调
 */
abstract class HttpCallback : Callback {

    override fun onFailure(p0: Call, p1: IOException) {
        //异常时，打印错误信息
        Log.e("HttpSmartCity", p1.localizedMessage)
    }

    override fun onResponse(p0: Call, p1: Response) {
        if (p1?.body() == null) {
            //处理响应为空的情况
            onFailure(p0, IOException("Response is empty"))
        } else {
            //响应不为空时，返回json字符串
            onSucceeded(p1.body()!!.string())
        }
    }

    /**
     * @Author: Tailyou(祝文飞)
     * @CreateDate: 2021/10/7 16:15
     * @Description: 请求成功，返回反序列化后的数据
     */
    abstract fun onSucceeded(data: String)

}

